package com.pig4cloud.pig.module.service.wx.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.TransactionalException;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.wx.WxAppPay;
import com.pig4cloud.pig.module.api.entity.*;
import com.pig4cloud.pig.module.api.entity.wx.UserSignRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxPayTransaction;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.mapper.wx.UserSignRecordMapper;
import com.pig4cloud.pig.module.service.base.ISignRoleService;
import com.pig4cloud.pig.module.service.wx.IUserSignRecordService;
import com.pig4cloud.pig.module.service.wx.IWxPayTransactionService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserSignRecordServiceImpl extends ServiceImpl<UserSignRecordMapper, UserSignRecord> implements IUserSignRecordService {
    @Resource
    private UserSignRecordMapper userSignRecordMapper;
	@Resource
	private ISignRoleService signRoleService;
	@Resource
	private IWxUserService wxUserService;
	@Resource
	private IWxPayTransactionService payTransactionService;


	@Value("${web.appid}")
	private String appid;
	@Value("${web.appidMp}")
	private String appidMp;
	@Value("${web.secret}")
	private String secret;
	@Value("${web.secretMp}")
	private String secretMp;
	@Value("${web.mch_id}")
	private String mch_id;
	@Value("${web.api_key}")
	private String api_key;
	@Value("${web.keyPath}")
	private String keyPath;//微信支付的回调地址


	@Override
	public Page<UserSignRecord> selectRecordList(Page<UserSignRecord> page, Map<String, Object> map) {
		return userSignRecordMapper.selectRecordList(page,map);
	}


	@Override
	public Double selectCashMoney(Map<String, Object> map) {
		return userSignRecordMapper.selectCashMoney(map);
	}

	@Override
	public List<UserSignRecord> selectRecordListExport(Map<String, Object> map) {
		return userSignRecordMapper.selectRecordListExport(map);
	}



	@Override
    public UserSignRecord selectBySignDate(Integer user_id, String sign_date) {
        QueryWrapper<UserSignRecord> qw = new QueryWrapper<>();
        qw.eq("user_id",user_id);
        qw.eq("sign_date",sign_date);
        qw.last("limit 1");
        return userSignRecordMapper.selectOne(qw);
    }

    @Override
    public UserSignRecord selectLastRecordByUserId(Integer user_id) {
        QueryWrapper<UserSignRecord> qw = new QueryWrapper<>();
        qw.eq("user_id",user_id);
        qw.last("limit 1");
        qw.orderByDesc("create_time");
        return userSignRecordMapper.selectOne(qw);
    }

    @Override
    public UserSignRecord selectTodayByUserId(Integer user_id) {
        QueryWrapper<UserSignRecord> qw = new QueryWrapper<>();
        qw.eq("user_id",user_id);
        qw.between("create_time", DateUtils.getDay() + " 00:00:00", DateUtils.getDay() + " 23:59:59");
        qw.last("limit 1");
        return userSignRecordMapper.selectOne(qw);
    }

	/**
	 *  重新打款
	 * @param signRecord
	 * @return
	 */
	@Override
	public int resetCash(UserSignRecord signRecord) {
		int ret = 0;
		try{
			SignRole signRole = signRoleService.getRoleByDayIndex(signRecord.getSignIndex() + 1);
			if(signRole!=null) {
				double cashMoney = signRecord.getCashMoney().doubleValue();
				if (cashMoney > 0) {
					String remark = "签到奖励";
					if(signRecord.getOpenId() == null){
						WxUser wxUser = wxUserService.findById(signRecord.getUserId());
						if(wxUser!=null){
							signRecord.setOpenId(wxUser.getOpenId());
						}
					}
					WxAppPay wxAppPay = new WxAppPay("", secret, appid, mch_id, api_key);
					Map<String, String> retRequest = wxAppPay.weixinChangePay(signRecord.getTradeNo(), signRecord.getCashMoney(), signRecord.getOpenId(), keyPath, remark);
					if (retRequest.containsKey("return_code")) {
						String result_code = retRequest.get("result_code");
						String err_code_des = retRequest.containsKey("err_code_des") ? retRequest.get("err_code_des") : "";
						signRecord.setResultCode(result_code);
						if (result_code.equals("SUCCESS")) {
							signRecord.setPayState(1);//支付成功
							signRecord.setErrCodeDes(err_code_des);


							WxUser wxUser = wxUserService.findById(signRecord.getUserId());
							// 添加 微信支付的 动账记录
							WxPayTransaction transaction = new WxPayTransaction();
							transaction.setPayType(0);// 0 -微信支付
							transaction.setTransactionId(signRecord.getTradeNo());
							transaction.setUserId(wxUser.getId());
							transaction.setFeeType("sign");
							transaction.setTotalMoney(signRecord.getCashMoney());
							if(StrUtil.isNotEmpty(wxUser.getNickName())){
								transaction.setNickName(EmojiParser.parseToAliases(wxUser.getNickName()));
							}
							transaction.setCreateTime(new Date());
							transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
							transaction.setRemark("签到现金奖励,重新打款");
							payTransactionService.save(transaction);


						} else {
							signRecord.setPayState(2);//支付失败
							signRecord.setErrCodeDes(err_code_des);
						}
						String pay_str = retRequest.get("pay_str");
						String reback_str = retRequest.get("reback_str");
						signRecord.setPayStr(pay_str);
						signRecord.setRebackStr(reback_str);

						ret = userSignRecordMapper.updateById(signRecord);
						if (ret <= 0) {
							throw new TransactionalException("cashRecordMapper system error");
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("addCashRecord system error");
		}
		return ret;
	}
}
